package com.zens.cms.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import com.zens.cms.entity.TColumn;
import com.zens.cms.entity.WebsiteInfo;
import com.zens.cms.services.IArticle;
import com.zens.cms.services.IWebsiteInfo;

/***
 * mobile json controller
 * @author xiangzc@evmtv.com
 * @date 2013-8-15
 */
@Controller
public class ArticleMobileControlller {
	
	private StringBuffer sb;
	 
	@Resource
	IArticle iArticle;
	@Resource
	IWebsiteInfo iWebsiteInfo;
	
	@RequestMapping("/indexSource")
	public String indexSource(Model model,String siteName){
		sb = new StringBuffer(500);
		
		if(StringUtils.hasText(siteName)){
			WebsiteInfo info = iWebsiteInfo.query(siteName);
			if(null != info){
				List<TColumn> colList = iArticle.getAllTcolumnByWebSiteId(info.getId());
				List<TColumn> level_1 = new ArrayList<TColumn>();
				List<TColumn> level_2 = new ArrayList<TColumn>();
				for(int i = 0,leng = colList.size();i < leng; i++){
					if(colList.get(i).getFcolumnlevel() == 1){
						level_1.add(colList.get(i));
					}else if(colList.get(i).getFcolumnlevel() == 2){
						level_2.add(colList.get(i));
					}
				}
				
				for(int j = 0,len = level_1.size();j < len;j ++){
					sb.append("[");
					loadChildSource(level_2, level_1.get(j).getId());
					sb.append("]");
					
					if(j < (len - 1)){
						sb.append(",");
					}
				}
				
			}
		}
		model.addAttribute("result", sb.toString());
		return "/json";
	}
	
	public void loadChildSource(List<TColumn> list,Long parent){
		StringBuffer buffer = new StringBuffer(500);
		for(int i = 0,len = list.size();i < len; i++){
			if(list.get(i).getFcolumngp().toString().intern() == parent.toString().intern()){
				buffer.append("{'name':'"+ list.get(i).getFcolumnname() +"','seek':false,'url':'" + parent + "'},");
				
			}
		}
		sb.append(buffer.toString().substring(0, buffer.toString().length() - 1));
	}

}
